<template>
  <div class="check-film-page">
    <modal-view
      title="影人库"
      v-model:visible="statusState.checkMakerVisible"
      size="small"
      okText="确定"
      cancelText="取消"
      :width="1006"
      @confirm="makerConfirm"
      @cancel="makerCancel"
    >
      <div class="filter-box">
        <a-input
          v-model:value.trim="makerState.person_id"
          :maxlength="19"
          :onkeyup="
            () => {
              if (makerState.person_id) makerState.person_id = makerState.person_id.replace(/\D/g, '')
            }
          "
          :onafterpaste="
            () => {
              if (makerState.person_id) makerState.person_id = makerState.person_id.replace(/\D/g, '')
            }
          "
          class="width-196 m-l-24"
          placeholder="请输入影人ID"
        />
        <a-input
          v-model:value.trim="makerState.person_keyword"
          class="width-196 m-l-24"
          placeholder="请输入影人名称关键词"
        />
      </div>
      <a-table
        id="classifyTable"
        :columns="makerColumn"
        :data-source="state.makerList"
        :loading="state.loading"
        :pagination="false"
        :scroll="{ x: 600 }"
      >
        <template #bodyCell="{ column, record }">
          <template v-if="column.key === 'person_gender'">
            <span>
              {{ getGender(record) }}
            </span>
          </template>
          <template v-else-if="column.key === 'person_video_count'">
            <span>
              {{
                !record.person_video_count || record.person_video_count === '0'
                  ? '-'
                  : formatNumber(record.person_video_count)
              }}
            </span>
          </template>
          <template v-else-if="column.key === 'action'">
            <span>
              <a class="basicColor" @click="addItem(record)">添加 </a>
            </span>
          </template>
        </template>
      </a-table>
      <a-pagination
        @change="handlePaginationChange"
        show-size-changer
        :defaultPageSize="10"
        :pageSizeOptions="['10', '20', '50', '100']"
        :show-total="(total:number)=>`共${total}条`"
        class="flex justify-end mt-[8px]"
        :total="queryState.total"
      />
    </modal-view>
  </div>
</template>
<script lang="ts" setup>
import type { MakerListData } from '@/types/site/role'
import { formatNumber } from '@/utils/format'
import { computed, onMounted, reactive, watch } from 'vue'
import { makerColumn } from './dataSource'
import ModalView from '@/components/components/modal/ModalView.vue'
import { roleState, statusState } from '../../state'
import apis from '@/apis'
import { storage } from '@/utils/storage'
const {
  site: { maker_list }
} = apis
const emit = defineEmits(['getMaker'])
const props = withDefaults(defineProps<{ personName?: any }>(), {
  personName: undefined
})
const siteId = storage.get('siteId')
const state = reactive({
  loading: false,
  makerList: [] as MakerListData[]
})
const queryState = reactive({
  offset: 0, // 默认当前页数
  limit: 10, // 默认当前页显示数据的大小
  total: 0 // 总数，必须先有
})
interface MakerState {
  //影人ID
  person_id: string | undefined
  // 关键词
  person_keyword: string | undefined
  site_id: string
  person_status: number
}
const makerState = reactive<MakerState>({
  person_id: '',
  person_keyword: '',
  site_id: siteId,
  person_status: 1
})

/**
 * 分页改变事件
 */
const handlePaginationChange = (size: number, limit: number) => {
  queryState.limit = limit
  queryState.offset = (size - 1) * limit
  getPersonList()
}
//查询影人
const getPersonList = () => {
  state.loading = true
  const params = { ...makerState, ...queryState }
  if (!params.person_id) params.person_id = undefined
  maker_list(params)
    .then((res: any) => {
      state.makerList = res?.persons ?? []
      queryState.total = +res?.total ?? 0
      state.loading = false
      //处理下一页，第一条删除问题
      if (queryState.offset >= (res?.persons ?? 0) && queryState.total != 0) {
        queryState.offset -= queryState.limit
        getPersonList()
      }
    })
    .catch(() => {
      state.loading = false
    })
}
//防抖
const antiShake = (id: any, keyword: any, time: number) => {
  return setTimeout(() => {
    console.log(`防抖：${id}-${keyword}`)
    getPersonList()
  }, time)
}
let timer: any = null
watch([() => makerState.person_id, () => makerState.person_keyword], (value) => {
  if (value) {
    console.log('value: ', value)
    clearTimeout(timer)
    timer = antiShake(value[0], value[1], 500)
  }
})
const makerConfirm = (value: any) => {
  console.log('value: ', value)
  statusState.checkMakerVisible = value
}
const makerCancel = () => {
  statusState.checkMakerVisible = false
}
const addItem = (item: any) => {
  emit('getMaker', item)
  statusState.checkMakerVisible = false
}
//获取性别
const getGender = computed(() => (item: any) => {
  if (item.person_gender === 1) return '男'
  if (item.person_gender === 2) return '女'
  return '-'
})
watch(
  () => props.personName,
  (val: any) => {
    console.log('val: ', val)
    if (val) {
      makerState.person_keyword = val
    }
  },
  { deep: true }
)
watch(
  () => statusState.checkMakerVisible,
  () => {
    getPersonList()
  },
  { deep: true }
)
onMounted(() => {})
</script>

<style lang="less" scoped>
.filter-box {
  display: flex;
  justify-content: flex-end;
  align-items: center;
  margin-bottom: 16px;

  .width-196 {
    width: 196px;
  }

  .m-l-24 {
    margin-left: 24px;
  }
}
</style>
